package main;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import ui.MainWindow;

public class Common 
{
	public static String m_indent = " ";
	public static String m_path = "./";
	
	public static boolean m_hasUI = false;
	
	public static void print(String message)
	{
		if(m_hasUI)
		{
			MainWindow.instance().addText(message);
		}
		else
		{
			System.out.println(message);
		}
	}
	
	public static String getExtendName(String path)
	{
		for(int i = path.length() - 1; i >= 0 ; --i)
		{
			char ch = path.charAt(i);
			if(ch == '.')
			{
				if(i < path.length() - 1)
				{
					return path.substring(i + 1);
				}
			}
			else if(ch == '/' || ch == '\\')
			{
				return null;
			}
		}
		return null;
	}
	
	public static String getNameWithoutExtented(String path)
	{
		for(int i = path.length() - 1; i >= 0 ; --i)
		{
			char ch = path.charAt(i);
			if(ch == '.')
			{
				for(int j = i - 1; j >= 0; --j)
				{
					ch = path.charAt(j);
					if(ch == '/' || ch == '\\')
					{
						if(j == i - 1)
						{
							return null;
						}
						return path.substring(j + 1, i);
					}
				}
				return path.substring(0, i);
			}
			else if(ch == '/' || ch == '\\')
			{
				if(i == path.length() - 1)
				{
					return null;
				}
				return path.substring(i + 1);
			}
		}
		return path;
	}
	
	public static String getPath(String path)
	{
		for(int i = path.length() - 1; i >= 0 ; --i)
		{
			char ch = path.charAt(i);
			if(ch == '/' || ch == '\\')
			{
				return path.substring(0, i + 1);
			}
		}
		return "";
	}
	
	public static Integer isInt(String num)
	{
		int rad = 10;
		if(num.length() > 1 && num.substring(0, 2).toLowerCase().compareTo("0x") == 0)
		{
			num = num.substring(2);
			rad = 16;
		}
		try 
		{
			return Integer.parseInt(num, rad);
		}
		catch(Exception e) 
		{
			return null;
		}
	}
	
	public static Double isDouble(String num)
	{
		int rad = 10;
		if(num.length() > 1 && num.substring(0, 2).toLowerCase().compareTo("0x") == 0)
		{
			num = num.substring(2);
			rad = 16;
		}
		try 
		{
			if(rad == 16)
			{
				Integer i = Integer.parseInt(num, 16);
				return new Double(i);
			}
			return Double.parseDouble(num);
		}
		catch(Exception e) 
		{
			return null;
		}
	}
	
	public static void saveToFile(StringBuffer text, String path, boolean isAppend) throws ErrorException
	{
		BufferedWriter writer = null;
		try 
		{
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, isAppend), "UTF-8"));
			writer.write(text.toString());
			writer.flush();
		} 
		catch(Exception e) 
		{
			throw new ErrorException(ErrorDefine.E_CANT_WRITE_FILE_ERR, path);
		}
		finally
		{
			try 
			{
				if(writer != null)
				{
					writer.close();
				}
			} 
			catch(Exception e2) 
			{
			}
		}
	}
}
